﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace FastGPT_Admin.Tool
{
    internal class AES256Helper
    {
        // AES加密密钥长度
        private const int AES_KEY_SIZE = 256;
        private const int IV_SIZE = 128;

        // 创建加密服务提供程序
        private Aes CreateAes()
        {
            Aes aes = Aes.Create();
            aes.KeySize = AES_KEY_SIZE;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            return aes;
        }

        // 将字符串密钥和IV转换为字节形式
        private (byte[] Key, byte[] IV) ConvertKeys(string key, string iv)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] ivBytes = Encoding.UTF8.GetBytes(iv);

            // 确保密钥长度正确
            if (keyBytes.Length != 32)
            {
                throw new ArgumentException("The key must be 32 bytes long.");
            }

            // 确保IV长度正确
            if (ivBytes.Length != 16)
            {
                throw new ArgumentException("The IV must be 16 bytes long.");
            }

            return (keyBytes, ivBytes);
        }

        // 将字节数组转换为十六进制字符串
        private string ToHex(byte[] bytes)
        {
            StringBuilder hex = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                hex.AppendFormat("{0:X2}", b);
            }
            return hex.ToString();
        }

        // 将十六进制字符串转换回字节数组
        private byte[] FromHex(string hex)
        {
            int numberChars = hex.Length;
            byte[] bytes = new byte[numberChars / 2];
            for (int i = 0; i < numberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }
            return bytes;
        }

        // AES加密
        public string EncryptToHex(string plainText, string key, string iv)
        {
            (byte[] keyBytes, byte[] ivBytes) = ConvertKeys(key, iv);
            using (Aes aes = CreateAes())
            {
                aes.Key = keyBytes;
                aes.IV = ivBytes;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            sw.Write(plainText);
                        }
                        byte[] encrypted = ms.ToArray();
                        return ToHex(encrypted);
                    }
                }
            }
        }

        // AES解密
        public string DecryptFromHex(string cipherTextHex, string key, string iv)
        {
            byte[] cipherText = FromHex(cipherTextHex);
            (byte[] keyBytes, byte[] ivBytes) = ConvertKeys(key, iv);

            using (Aes aes = CreateAes())
            {
                aes.Key = keyBytes;
                aes.IV = ivBytes;

                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                using (MemoryStream ms = new MemoryStream(cipherText))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            return sr.ReadToEnd();
                        }
                    }
                }
            }
        }

        public static void MainTest()
        {

            AES256Helper helper = new AES256Helper();
            string plainText = "要加密的文本";
            string key = "mysecretkey123456789012345"; // 必须是32个字符长
            string iv = "mysecretiv123456"; // 必须是16个字符长

            // 加密
            string encryptedHex = helper.EncryptToHex(plainText, key, iv);
            Console.WriteLine("加密后的十六进制字符串: " + encryptedHex);

            // 解密
            string decryptedText = helper.DecryptFromHex(encryptedHex, key, iv);
            Console.WriteLine("解密后的文本: " + decryptedText);
        }
    }
}
